import {PlusOutlined} from '@ant-design/icons';
import {Button, Form, FormInstance, message, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
import {list, page, removeById, save} from '../service/baseService';
import {DataEntity} from "@/assets/entity/base";
import {TableListProps} from "@/assets/components/tableListProps";
import "./index.css";
import ModalForm from "@/assets/components/modalForm";
import {Link} from "react-router-dom";

/**
 * 添加/保存节点
 * @param form
 * @param moduleUrl
 * @param handleModalVisible
 * @param actionRef
 * @param successCallback
 */
export const handleSave = async (form: FormInstance, moduleUrl: string, handleModalVisible?: any, actionRef?: any, successCallback?: any) => {
  // 判断是否为添加，此次记录id为空则为添加，否则为更新
  let makeType: string;
  if (form.getFieldValue("id")) {
    makeType = "更新"
  } else {
    makeType = "添加"
  }

  const hide = message.loading('正在' + makeType);
  form.validateFields().then(async () => {
    await save(moduleUrl, form.getFieldsValue());
    hide();
    message.success(makeType + '成功');
    handleModalVisible && handleModalVisible(false)
    // 重载表格
    actionRef && actionRef.current?.reload();
    successCallback && successCallback()
    return true;
  }).catch((errorInfo) => {
    console.log(errorInfo)
    if(errorInfo.errorFields.length === 0){
      console.log("BUG")
      save(moduleUrl, form.getFieldsValue());
    }
    hide();
  })
};

/**
 *  删除单个节点
 * @param id
 * @param moduleUrl
 * @param actionRef
 * @param successCallback
 */
export const handleRemove = async (id: string | undefined, moduleUrl: string, actionRef?: any, successCallback?: any) => {
  const hide = message.loading('正在删除');
  if (!id) return true;
  try {
    await removeById(moduleUrl, id);
    hide();
    message.success('删除成功，即将刷新');
    // 重载表格
    actionRef && actionRef.current?.reload();
    successCallback && successCallback()
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请联系管理员');
    return false;
  }
};

/**
 * 面包屑ItemRender，使用 browserHistory需要注入该函数
 * @param route
 * @param params
 * @param routes
 * @param paths
 */
export const breadcrumbItemRender = (route: any, params: any, routes: any, paths: any) => {
  const last = routes.indexOf(route) === routes.length - 1;
  return last ? (
    <span>{route.breadcrumbName}</span>
  ) : (
    <Link to={route.path} key={routes.indexOf(route)}>{route.breadcrumbName}</Link>
  );
}

/**
 * 列表组件
 * @param props
 * @constructor
 */
const TableList = (props: TableListProps) => {
  const [formModalVisible, handleModalVisible] = useState<boolean>(false);
  const [modalFormValues, setModalFormValues] = useState({});
  const actionRef = props.actionRef || useRef<ActionType>();
  const form = props.form || Form.useForm()[0];
  const moduleUrl: string = props.moduleUrl;
  const title: String = props.title;
  const editInitial = props.editInitial;
  const columns: ProColumns<DataEntity>[] = props.columns || [];
  const changeColumns = props.changeColumns;

  const searchRef =  props.searchRef || useRef<FormInstance>();

  /**
   * 操作行
   */
  const optionColumn: ProColumns<DataEntity> = {
    title: '操作',
    valueType: 'option',
    width: props.extraOption ? 150 : 100,
    render: (_: any, record: DataEntity) => {
      // 编辑按钮
      let editOption;
      // 判断是否需要编辑
      if (!props.isNotShowEditOption) {
        // 默认需要
        // 判断是否使用弹框form
        if (!props.isNotUseModalForm) {
          editOption = props.editOption ? props.editOption(record) : <a
            onClick={() => {
              // editInitial && editInitial(columns, setColumns, record);
              form.setFieldsValue(record)
              // 复杂类型重新单独set
              for (let key in record) {
                let value = record[key];
                if (value && value.constructor === Object) {
                  form.setFieldsValue({[key + ".id"]: value.id})
                }
              }
              editInitial && editInitial(record, form);
              handleModalVisible(true)
            }}
          >
            编辑
          </a>;
        } else {
          editOption = <Link to={props.formUrl ? props.formUrl(record.id) : moduleUrl + "/form/" + record.id}>编辑</Link>
        }
      }
      // 判断是否需要删除
      let deleteOption;
      if (!props.isNotShowDeleteOption) {
        // 默认需要
        deleteOption = <a onClick={() => {
          Modal.confirm({
            title: '删除',
            content: '确定删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => handleRemove(record.id, moduleUrl, actionRef),
          });
        }}
        >
          删除
        </a>;
      }
      // 如果有额外的操作按钮，则添加，默认到最前面
      const optionButton = [props.extraOption && props.extraOption(record), editOption, deleteOption];
      return optionButton;
    },
  };

  useEffect(function () {
    // 加上操作行
    if (props.isNotShowOption !== true) {
      changeColumns(columns.slice().concat(optionColumn))
    }
  }, [])

  return (
    <PageContainer
      title={title}
      header={{
        breadcrumb: {
          routes: props.breadcrumbRoutes,
          itemRender: breadcrumbItemRender
        }
      }}
    >
      <ProTable
        // 树形数据默认展开
        expandable={{defaultExpandAllRows: true}}
        rowClassName={props.rowClassName}
        onRow={props.onRow}
        headerTitle={title}
        tableClassName={props.tableClassName}
        actionRef={actionRef}
        formRef={searchRef}
        rowKey="id"
        params={props.params}
        scroll={{x: 'max-content'}}
        search={{
          labelWidth: 80,
          optionRender: props.searchOptionRender,
          defaultCollapsed:false
        }}
        toolBarRender={() => {
          let toolBars = [];
          // 判断是否需要有添加功能
          if (!props.isNotCanAdd) {
            let addOption;
            // 如果有addOption则不显示默认的新建
            if (props.addOption) {
              addOption = props.addOption;
            } else {
              // 判断是否使用弹框form
              if (!props.isNotUseModalForm) {
                // 如果有addOption则不显示默认的新建
                addOption = <Button type="primary" onClick={() => {
                  let addFunctionResult: boolean = true;
                  addFunctionResult = props.addFunction && props.addFunction();
                  if (addFunctionResult || addFunctionResult === undefined) {
                    setModalFormValues(() => {
                    })
                    handleModalVisible(true);
                  }
                }}>
                  <PlusOutlined/> 新建
                </Button>
              } else {
                // 不使用弹框
                addOption = <Button type={"primary"}>
                  <Link to={props.formUrl ? props.formUrl(0) : moduleUrl + "/form/" + "0"}><PlusOutlined/> 新建</Link>
                </Button>
              }
            }
            toolBars.push(addOption)
          }
          return toolBars;
        }}
        request={
          (params, sorter, filter) =>
            props.request ? props.request(params, sorter, filter, searchRef) : (props.isFindPage === true ? page(moduleUrl, {...params}) : list(moduleUrl, {...params}))
        }
        columns={columns}
      />
      {
        !props.isNotUseModalForm &&
        <ModalForm
          form={form}
          columns={columns}
          values={modalFormValues}
          visible={formModalVisible}
          extraButton={props.formExtraButton}
          handleSave={() => handleSave(form, moduleUrl, handleModalVisible, actionRef)}
          onCancel={() => handleModalVisible(false)}
          extraFormItems={props.formExtraFormItems}
        />
      }
    </PageContainer>
  )
};

export default TableList;
